package me.zingon.doc.controller;

import javax.servlet.http.HttpServletRequest;

import me.zingon.doc.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import me.zingon.doc.exception.ServiceException;
import me.zingon.doc.model.LcManager;
import me.zingon.doc.util.JwtUtil;

@Component
public class BaseController {
    @Autowired
    HttpServletRequest request;
    @Value("${jwt.header.token}")
    String TokenKey;

    public LcManager getManager() throws ServiceException {
    	String token = request.getHeader(TokenKey);
        Claims claims = JwtUtil.validate(token);
        if (null == claims){
            throw new ServiceException("login.invalid");
        }
        Integer managerId = (Integer)claims.get("mangerId");   
        String loginName = (String)claims.get("loginName");
        LcManager manager = new LcManager();
        manager.setId(managerId);
        manager.setLoginName(loginName);
        return manager;
    }

    public User getUser() throws ServiceException {
        String token = request.getHeader(TokenKey);
        Claims claims = JwtUtil.validate(token);
        if (null == claims){
            throw new ServiceException("login.invalid");
        }
        Integer userId = (Integer)claims.get("userId");
        String loginName = (String)claims.get("loginName");
        String nickName = (String)claims.get("nickName");
        User user = new User();
        user.setId(userId)
                .setLoginName(loginName)
                .setNickname(nickName);
        return user;
    }

}
